import { CustomTableInterface } from '@/components/ProTable/interface';
import { PublicInterface } from '@/interface/public';
import { buttonProps } from '@/components/GlobalButton/interface';
import { useAddForm } from '../form/use-addForm';
import { useLeaveForm } from '../form/use-leaveForm';
import { useChangeTypeForm } from '../form/use-changeTypeForm';
import { useChangeDeptForm } from '../form/use-changeDeptForm';
import { dayjs } from 'element-plus';
import { FormKeys } from '@/components/ProForm/interface';
import { RosterInterface } from '@/api/interface/personnel/roster/roster';
import { formGetChildren } from '@/utils/form';
import { PublicParams } from '@/api/interface/publicParams';

interface DrawerObjProp {
  visible: boolean;
  flag: 'edit' | 'add';
  id: number;
}

export function useDataGrid(proTableBox: PublicInterface.ProTableValue, proFormBox: PublicInterface.ProFormValue) {
  const { addForm, saveAddForm } = useAddForm(proTableBox, proFormBox);
  const { leaveForm, saveLeaveForm } = useLeaveForm(proTableBox);

  const { saveAddChangeTypeForm, changeTypeForm } = useChangeTypeForm(proTableBox);
  const { saveAddChangeDeptForm, changeDeptForm, setDeptChildren } = useChangeDeptForm(proTableBox);

  /**
   * 附件上传
   */
  const { fileObj, setFileId } = useCommonFile({
    downloadPermissionCode: 'ehr:fileDownload',
    deletePermissionCode: 'ehr:fileDelete',
    upLoadingPermissionCode: 'ehr:fileUploading',
    previewPermissionCode: 'ehr:filePreview'
  });

  /**
   * 抽屉配置项
   */
  let drawerObj = ref<DrawerObjProp>({
    visible: false,
    flag: 'add',
    id: null
  });
  /**
   * 打印相关信息
   */
  let printBox = ref({
    visible: false,
    row: {}
  });

  /**
   * tabs配置项
   */
  const tabsObj = ref({
    activeName: 'basic',
    names: ['basic', 'familyInfo', 'workExperience', 'educationExperience', 'financialInfo', 'contractInformation', 'otherInfo']
  });

  /**
   * 住宿详情
   */
  const stayDetail = ref<any>({
    visible: false,
    data: []
  });

  const formBottomButton: buttonProps[] = [
    {
      label: '保存',
      type: 'primary',
      display: () => tabsObj.value.activeName === 'basic',
      methods: () => {
        saveAddForm().then((flag: any) => {
          if (flag) {
            drawerObj.value.id = flag.id;
          }
        });
      }
    }
  ];

  let dataGrid = reactive<CustomTableInterface<RosterInterface.ResRosterPageList>>({
    initParam: {
      queryType: 'NORMAL'
    },
    transitionArr: [
      {
        oldField: 'employeeType',
        newField: 'type'
      },
      {
        oldField: 'politicsStatus',
        newField: 'politicsStatus'
      },
      {
        oldField: 'gender',
        newField: 'gender'
      },
      {
        oldField: 'education',
        newField: 'education'
      },
      {
        oldField: 'marriageStatus',
        newField: 'marriageStatus'
      },
      {
        oldField: 'recruitSource',
        newField: 'recruitSource'
      }
    ],
    // 表格配置项
    columns: [
      { prop: 'operation', label: 'operation', fixed: 'left', width: 180 },
      {
        isShow: false,
        prop: 'key',
        search: {
          el: 'input',
          label: '关键值',
          props: {
            placeholder: ' 身份证 | 姓名 | 手机号 | 备注'
          }
        }
      },

      {
        prop: 'type',
        label: '员工类型',
        enum: [],
        search: {
          el: 'select'
        }
      },
      {
        isShow: false,
        prop: 'overMonth',
        search: {
          el: 'date-picker',
          label: '当月过生人员',
          props: {
            type: 'month',
            valueFormat: 'MM',
            format: 'MM'
          }
        }
      },
      {
        isShow: false,
        prop: 'flagNormal',
        enum: statusYesOrNo,
        search: {
          el: 'select',
          label: '是否转正'
        }
      },

      {
        isShow: false,
        prop: 'normalMonth',
        search: {
          el: 'date-picker',
          label: '转正月份',
          props: {
            type: 'month',
            valueFormat: 'YYYY-MM',
            format: 'YYYY-MM'
          }
        }
      },
      {
        isShow: false,
        prop: 'days',
        search: {
          el: 'input',
          defaultValue: 30,
          label: '查询天数'
        }
      },
      {
        isShow: false,
        prop: 'entryDate',
        search: {
          el: 'date-picker',
          label: '入职时间',
          props: {
            type: 'daterange',
            valueFormat: BasicKey.DATE_FORMAT.YYYY_MM_DD,
            format: BasicKey.DATE_FORMAT.YYYY_MM_DD
          }
        }
      },
      {
        label: '工号',
        prop: 'empNo'
      },
      {
        label: '姓名',
        prop: 'name'
      },

      {
        label: '入职日期',
        prop: 'entryDate',
        width: 100
      },
      {
        prop: 'entryDept',
        label: '入职部门'
      },
      {
        prop: 'entryJob',
        label: '入职岗位'
      },
      {
        prop: 'normalDate',
        label: '转正日期',
        width: 100
      },
      {
        label: '手机号',
        prop: 'phoneNumber',
        width: 100
      },
      {
        prop: 'politicsStatus',
        label: '政治面貌',
        enum: [],
        search: {
          el: 'select'
        }
      },
      {
        label: '状态',
        prop: 'status',
        enum: statusRoster,
        tag: true,
        search: {
          el: 'select',
          defaultValue: [0, 1],
          props: {
            multiple: true
          },
          label: '状态'
        }
      },
      {
        prop: 'remark',
        label: 'remark'
      }
    ],

    headButtonList: [
      {
        label: 'add',
        type: 'primary',
        icon: 'el-Plus',
        // permissionCode: 'operatorInfo:save',
        methods: () => {
          Object.assign(drawerObj.value, {
            visible: true,
            flag: 'add'
          });
          formChangeItemStatus(addForm, addForm.disabledPropList, false);
          formChangeItemStatus(addForm, addForm.hidePropList, true, 'hide');
          setDictionaries(addForm);
        }
      },
      {
        label: '住宿详情',
        type: 'primary',
        icon: 'stay',
        attrs: {
          plain: true
        },
        // permissionCode: 'roster:saveOther',
        methods: async () => {
          stayDetail.value.visible = true;
          // stayDetail.value.data = await rosterRosterGpDormitory();
          console.log('-----');
        }
      }
    ],
    rowButtonList: [
      {
        label: 'edit',
        type: 'primary',
        // permissionCode: 'roster:save',
        display: item => item.flagLeave === 0,
        methods: row => {
          edit(row);
        },
        attrs: {
          link: true
        }
      },
      {
        label: '提交',
        type: 'primary',
        // permissionCode: 'roster:commit',
        display: row => row.status === 0,
        attrs: {
          link: true
        },
        methods: async row => {
          useHandleData(
            rosterSubmit,
            { id: row.id },
            `提交 【${row.name}】花名册,提交后身份证号不可以直接修改,确定提交`,
            proTableBox.value?.getTableList
          );
        }
      },
      {
        label: '打印',
        type: 'primary',
        // permissionCode: "device:commit",
        // display: row => row.status === 0,
        attrs: {
          link: true
        },
        methods: row => {
          Object.assign(printBox.value, {
            visible: true,
            row
          });
        }
      },

      {
        label: 'delete',
        type: 'danger',
        // permissionCode: 'roster:remove',
        display: row => row.status === 0,
        methods: row => {
          const name = `${transitionLanguages('button', 'delete')}【${row.name}】登记信息`;
          useHandleData(rosterDelete, { id: row.id }, name, proTableBox.value?.getTableList);
        },
        attrs: {
          link: true
        }
      },
      {
        label: '更多',
        type: 'primary',
        icon: 'el-ArrowDown',
        attrs: {
          link: true
        },
        display: item => item.status === 1,
        children: [
          {
            label: '离职',
            // permissionCode: 'roster:leave',
            display: item => item.status === 1,
            methods: row => {
              setDictionaries(leaveForm);
              formOpen(leaveForm, '离职办理', row);
            },
            attrs: {
              link: true
            }
          },
          {
            label: '修改员工类型',
            // permissionCode: 'roster:changeType',
            display: item => item.status === 1,
            methods: row => {
              formOpen(changeTypeForm, '修改员工类型', row);
              setDictionaries(changeTypeForm);
            },
            attrs: {
              link: true
            }
          },
          {
            label: '岗位调换',
            // permissionCode: 'roster:changeDept',
            display: item => item.status === 1,
            methods: row => {
              formOpen(changeDeptForm, '岗位调换', row);
              formChangeItemStatus(changeDeptForm, changeDeptForm.disabledPropList, true);
              setDeptChildren(row.entryDeptId);
            },
            attrs: {
              link: true
            }
          }
        ]
      }
    ]
  });

  onMounted(() => {
    tableSetDictionariesEnum(dataGrid);
  });

  /** 表格行点击 */
  const dataGridCellClick = ({ row }) => {
    edit(row);
  };

  const dataCallback = (data: PublicParams.ResPage<RosterInterface.ReqRosterPageList>) => {
    data.records.forEach(item => {
      item.checkInDate = dayjs().format('YYYY 年 MM 月 DD 日');
    });
    return data;
  };

  const edit = async row => {
    Object.assign(drawerObj.value, {
      visible: true,
      flag: 'edit',
      id: row.id
    });

    setFileId(row.id);

    tabsObj.value.activeName = 'basic';
    await setDictionaries(addForm);
    formChangeItemStatus(addForm, addForm.hidePropList, true, 'hide');
    nextTick(() => {
      Object.assign(addForm.form, row);

      const { recruitSource, flagNormal, identityEnd } = addForm.form || {};

      let displayList: FormKeys<RosterInterface.ReqRosterSave>[] = [];

      // 是否是转正
      if (flagNormal === 1) {
        displayList.push('normalDate');
      }
      const children = formGetChildren<RosterInterface.ReqRosterSave>(addForm, ['recruitSource']);

      // 招聘来源 是否为其他类型
      const isOuterSourceStatus = children.get('recruitSource').find(item => item.value === recruitSource);

      if (recruitSource) {
        if (!isOuterSourceStatus) {
          addForm.form.otherRecruitSource = recruitSource;
          Object.assign(addForm.form, {
            recruitSource: '其他',
            otherRecruitSource: recruitSource
          });
          displayList.push('otherRecruitSource');
        }
      }

      //身份证是否永久有效
      if (identityEnd !== '2099-12-31') {
        addForm.form.idScope = '有截止日';
        displayList.push('identityEnd');
      } else {
        addForm.form.idScope = '永久';
      }

      if (displayList.length) {
        formChangeItemStatus(addForm, displayList, false, 'hide');
      }

      formChangeItemStatus(addForm, addForm.disabledPropList, true);
    });
  };

  return {
    dataGrid,
    addForm,
    saveAddForm,
    drawerObj,
    tabsObj,
    formBottomButton,
    leaveForm,
    saveLeaveForm,
    saveAddChangeTypeForm,
    changeTypeForm,
    saveAddChangeDeptForm,
    changeDeptForm,
    printBox,
    dataCallback,
    dataGridCellClick,
    stayDetail,
    fileObj,
    setFileId
  };
}
